#include "serveur.h"
#include "structures.h"
#include "neighbour.h"


int main(void) {
	int i, ret, fdmax, nbre_clients;
	int nbyte, size, val;
	char buf[BUFSIZE];
	int listenSock, client_sock;
	struct sockaddr_in sAddr, cAddr;
	identifiants  id_client;
	fd_set read_set, master_set;
	FILE* fd;

	/*identifiants defaut;
	defaut.port = 0;


	for (b = 0 ; b < max ; b++) {
	  table[b] = (identifiants *)malloc(sizeof(identifiants));
	  table[b]->port = 0;
	}

	printf("initialisation de la table\n");*/
	//protocole TCP/IP
	listenSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	CHK_ERR(listenSock,"socket");

	//option:liberer adrress utilise par le prog
	val = 1;
	ret = setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
	CHK_ERR(ret,"setsockopt");

	//adresse serveur
	memset(&sAddr, 0, sizeof(sAddr));
	memset(&cAddr, 0, sizeof(cAddr));
	sAddr.sin_family = AF_INET;
	sAddr.sin_addr.s_addr = inet_addr(IP);
	sAddr.sin_port = htons(PORT);

	size = sizeof(sAddr);
	ret = bind(listenSock, (struct sockaddr*)&sAddr, size);
	CHK_ERR(ret,"bind");

	ret = listen(listenSock, 5);
	CHK_ERR(ret, "listen");

	printf("serveur listen in ");
	print_addr(&sAddr);

	fdmax = listenSock;
	FD_ZERO(&read_set);
	FD_SET(listenSock, &master_set);

	if ((fd = fopen("neighbour.txt","w+")) == NULL)
		perror("erreur fopen neigh.txt");

	//boucle
	while(1)
	{
		read_set = master_set;
		ret = select(fdmax+1, &read_set,NULL,NULL,NULL);
		CHK_ERR(ret, "select");

		for(i=0; i<= fdmax; i++){
			if(FD_ISSET(i,&read_set)){ // socket i ayant activite read

				if(i == listenSock){
					size = sizeof(cAddr);
					client_sock = accept(listenSock, (struct sockaddr*)&cAddr, &size);
					if(client_sock == -1)
						perror("accept");
					else {
						printf("accept client ");
						nbre_clients++;
						print_addr(&cAddr);

						//Ajout des données clients pour Neighbourhood
						id_client.port = htons(cAddr.sin_port);
						id_client.ip.s_addr = inet_ntoa(cAddr.sin_addr);
						//propagation(&id_client);

						FD_SET(client_sock, &master_set);
						if(client_sock > fdmax)
							fdmax = client_sock;
					}
				} else {
					nbyte = recv(i, buf, BUFSIZE, MSG_DONTWAIT); //non bloquant
					if (nbyte <=0){
						if(nbyte == -1)
							perror("recv");
						if (nbyte == 0)
							close(i);
						FD_CLR(i,&master_set);
						printf("deconnection client \n");
					}
					else{ // cas de reception donne
						printf("recv = %s\n",buf);
						handle_cmd(buf, i, client_sock);
					}

				}
			}
		}
	}



	shutdown(listenSock, SHUT_RDWR);
	return 0;
}
